package org.lixf.servlets;

import org.lixf.AppConfig;
import org.lixf.controllers.LoginController;
import org.lixf.controllers.RegisterController;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// servlet由tomcat创建不能交给spring管理
@WebServlet(name = "dispatcher", urlPatterns = "/")
public class DispatcherServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(req.getMethod());
        // AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // applicationContext.register(AppConfig.class);
        // applicationContext.refresh();
        WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        String path = req.getServletPath();
        if ("/doLogin".equals(path)) {
            LoginController loginController = applicationContext.getBean(LoginController.class);
            loginController.doLogin(req, resp);
        } else if (("/doRegister".equals(path))) {
            RegisterController registerController = applicationContext.getBean(RegisterController.class);
            registerController.doRegister(req, resp);
        } else if (("/register".equals(path))) {
            req.getRequestDispatcher("/register.jsp").forward(req,resp);
        } else if (("/login".equals(path))) {
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        } else if (("/home".equals(path))) {
            req.getRequestDispatcher("/home.jsp").forward(req,resp);
        }
    }
}
